package com.rec.service.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.rec.entity.Readrooms;
import com.rec.repository.ReadroomsReposistory;
import com.rec.service.ReadRoomsService;
@Service
public class ReadroomsServiceImpl implements ReadRoomsService{
	@Autowired
	private ReadroomsReposistory r;
	@Override
	public Map<String, Object> all(Map<String, Object> params) {
		Specification<Readrooms> spec = getSpec(params);
		// 创建分页对象
		Integer page = (Integer) params.get("page");
		Integer limit = (Integer) params.get("limit");
		Pageable pa = PageRequest.of(page, limit);
		Page<Readrooms> result = r.findAll(spec,pa);
		List<Readrooms> data = result.getContent();
		long count = result.getTotalElements();
		if(data.size()>0) {
			params.put("code", 0);
			params.put("data", data);
			params.put("count", count);
			
		} else {
			params.put("code", 1);
			params.put("msg", "服务器走丢了！");
		}
		return params;
	}
	private Specification<Readrooms> getSpec(Map<String, Object> params) {
		return new Specification<Readrooms>() {
			@Override
			public Predicate toPredicate(Root<Readrooms> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate pre = cb.conjunction();
				List<Expression<Boolean>> sqlList = pre.getExpressions();
				if(!StringUtils.isEmpty(params.get("name"))) {
					sqlList.add(cb.like(root.get("name"),"%"+params.get("name")+"%"));
				}
				if(!StringUtils.isEmpty(params.get("remark"))) {
					sqlList.add(cb.like(root.get("remark"),"%"+params.get("remark")+"%"));
				}
				return pre;
			}
			
		};
	}
	@Override
	public Integer add(Readrooms readrooms) {
		Readrooms read = r.save(readrooms);
		if(read!=null) {
			return 1;
		}
		return 0;
	}

	@Override
	public Integer update(Readrooms readrooms) {
		Readrooms read = r.save(readrooms);
		if(read!=null) {
			return 1;
		}
		return 0;
	}

	@Override
	public Integer delete(Integer id) {
		try {
			   r.deleteById(id);
			return 1;
		} catch (Exception e) {
			System.out.println("删除失败");
			return 0;
		}
	}
	

}
